package cn.schoolwow.util.module.query.instance.service;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.query.instance.domain.InstanceQueryOption;
import org.apache.commons.lang3.Validate;

public class GetInstanceFieldsValueFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        getSingleFieldValue(flowContext);
        getMultipleFieldValue(flowContext);
    }

    public String name() {
        return "通过反射获取实例指定字段列表的值";
    }

    private void getSingleFieldValue(FlowContext flowContext){
        String[] fieldNames = (String[]) flowContext.checkData("fieldNames");

        if(fieldNames.length==1){
            flowContext.startFlow(new GetInstanceFieldValueFlow())
                    .putCurrentCompositeFlowData("fieldName", fieldNames[0])
                    .execute();
            flowContext.brokenCurrentFlow("获取单个属性的值");
        }
    }

    private void getMultipleFieldValue(FlowContext flowContext){
        String[] fieldNames = (String[]) flowContext.checkData("fieldNames");
        InstanceQueryOption instanceQueryOption = flowContext.checkInstanceData(InstanceQueryOption.class);

        if(fieldNames.length>1){
            StringBuilder builder = new StringBuilder();
            for(String fieldName:fieldNames){
                flowContext.startFlow(new GetInstanceFieldValueFlow())
                        .putCurrentCompositeFlowData("fieldName", fieldName)
                        .execute();
                Object fieldValue = flowContext.checkData("fieldValue");
                Validate.notNull(fieldValue, "实例值查询为空!实例类:"+instanceQueryOption.instance.getClass().getName()+",字段名:"+fieldName);
                builder.append(fieldValue+":");
            }
            builder.deleteCharAt(builder.length()-1);
            flowContext.putReturnData("fieldValue", builder.toString());
        }
    }
}
